import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'
import { closestCorners, DndContext } from "@dnd-kit/core"
import useWorkDrag from "./use-drag"
import DayWorks from "../day-works"
import dayjs, { Dayjs } from 'dayjs'
import { DatePicker, Spin, type DatePickerProps } from 'antd'
import { getDatesBetween } from 'packages/shared/utils/utils'
import './index.css'

export interface ModelCalendarProps {
    [x: string]: any
}
export interface ModelCalendarRef {
    load: (value: any[]) => void
}

const weekFormat = 'M/D'
const customWeekStartEndFormat: DatePickerProps['format'] = (value) =>
    `${dayjs(value).startOf('week').format(weekFormat)} ~ ${dayjs(value).endOf('week').format(weekFormat)}`

const ModelCalendar = forwardRef<ModelCalendarRef, ModelCalendarProps>((props: ModelCalendarProps, ref) => {
    const [loading, setLoading] = useState(false)
    useImperativeHandle(ref, () => {
        return {
            load: (data: any[]) => {
                setWorks(data)
            }

        }
    })
    const handleDateChange = (value?: Dayjs) => {
        setLoading(true)
        setTimeout(() => {
            const _value = value || dayjs()
            const start = dayjs(_value).startOf('week').format('YYYY-MM-DD')
            const end = dayjs(_value).endOf('week').format('YYYY-MM-DD')
            setWorks(getDatesBetween(start, end, weekFormat))
            setLoading(false)
        }, 1000)
    }
    const { containers, sensors, handleDragStart, handleDragEnd, setWorks } = useWorkDrag()
    useEffect(() => {
        handleDateChange()
    }, [])
    return (
        <div className='model-calendar'>
            <div className='model-calendar-query'>
                <DatePicker prefix='查询日期' defaultValue={dayjs()} format={customWeekStartEndFormat} onChange={handleDateChange} picker="week" />
            </div>
            <div className='model-calendar-body'>
                {
                    loading && <Spin size='large' style={{ position: 'absolute', zIndex: 1000, left: '50%', top: '50%' }}></Spin>
                }
                <DndContext sensors={sensors}
                    collisionDetection={closestCorners}
                    onDragStart={handleDragStart}
                    onDragEnd={handleDragEnd}>
                    <div className='week-works grid1-7'>
                        {
                            containers.map((container) => (
                                // <SortableContext items={container.items}>
                                <DayWorks key={container.id}
                                    data={container}></DayWorks>
                                // </SortableContext>
                            ))
                        }
                    </div>
                </DndContext>
            </div>
        </div>
    )
})

export default ModelCalendar